import jsPDF from "jspdf";
import { domToCanvas } from "./image";

export const generateAndDownloadPDF = async (dom: HTMLElement) => {
  try {
    const canvas = await domToCanvas(dom);

    const pdf = new jsPDF();

     // 定义缩放比例
     const scaleFactor = 0.7; // 缩放至原来的一半大小

     const pdfWidth = pdf.internal.pageSize.getWidth();
     const pdfHeight = pdf.internal.pageSize.getHeight();
    // 将Canvas添加到PDF中
    const imgData = canvas.toDataURL("image/png");
    const imgWidth = pdf.internal.pageSize.getWidth() * scaleFactor;
    const imgHeight = (canvas.height * imgWidth) / canvas.width;

    const offsetX = (pdfWidth - imgWidth) / 2; // 计算水平居中位置
    const offsetY = (pdfHeight - imgHeight) / 2; // 计算垂直居中位置



    pdf.addImage(imgData, "PNG", offsetX, offsetY, imgWidth, imgHeight);

    // 将PDF保存或提供下载
    const fileName = `${Date.now()}.pdf`;
    pdf.save(fileName);
  } catch (error) {
    console.error("生成PDF失败：", error);
  }
};
